#!/bin/bash
set_ssh() {
#检查本地是否生成公钥
if [ -e $HOME/.ssh/id_rsa ];then
   read -p "输入你要进行免密登录的IP  " address
   ping -c1 -W 1 ${address} &> /dev/null
   if [ $? -ne 0 ] ;then
      echo -e "\e[33m${address}不能正常通信\e[0m"
   else
      read  -p "输入你要使用的用户(默认为root)  " user
      read  -s -p "输入${address}的${user:-root}用户的密码  " password
      #安装expect软件包
      yum -y install expect &> /dev/null && echo -e  "\e[32m安装完毕！\e[0m"  || echo -e "\e[31m安装失败\e[0m"
      #删除已知主机文件，防止后面程序受影响
      rm -rf $HOME/.ssh/known_hosts
      #使用expect自动化完成公钥传递
 expect << EOF
  spawn ssh-copy-id ${user:-root}@$address;
  expect {
  "Are you sure you want to continue connecting (yes/no)?" {
    send "yes\r"
    exp_continue
  }
  "password:" {
    send "$password\r"
  }
eof
}
EOF
fi
else
   echo "公钥未生成"
fi 
}


